<template>
  <el-dialog
    v-model="visible"
    :title="institutionName"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="800px"
    class="institution-dialog"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      label-width="120px"
      label-position="top"
      @keyup.enter="submitForm()"
    >
      <div class="form-content">
        <el-form-item label="资质证书:" class="upload-item">
          <div class="upload-container">
            <el-upload
              action=""
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :before-remove="beforeRemove"
              :limit="5"
              multiple
              :file-list="fileList"
              :auto-upload="false"
              accept="image/*"
              class="qualification-upload"
            >
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-tip">点击上传机构相关图片</div>
              <template #file="{ file }">
                <div class="uploaded-image">
                  <img
                    class="uploaded-image-el"
                    :src="file.url"
                    alt=""
                    @click="handlePictureCardPreview(file)"
                  />
                  <div class="uploaded-image-actions">
                    <span
                      class="uploaded-image-delete"
                      @click.stop="handleRemove(file)"
                    >
                      <el-icon><Delete /></el-icon>
                    </span>
                  </div>
                </div>
              </template>
            </el-upload>
            <div class="upload-hint">
              <div class="hint-title">上传要求</div>
              <ul class="hint-list">
                <li>支持 JPG/PNG 格式</li>
                <li>每张图片不超过5MB</li>
                <li>最多可上传5张图片</li>
                <li>图片清晰可见，内容完整</li>
              </ul>
              <div class="upload-progress" v-if="uploadingCount > 0">
                <div class="progress-text">
                  正在上传 {{ uploadingCount }}/{{ fileList.length }} 张图片...
                </div>
                <el-progress
                  :percentage="uploadProgress"
                  :stroke-width="4"
                  :show-text="false"
                />
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="相关介绍:" prop="content" class="description-item">
          <el-input
            type="textarea"
            rows="5"
            v-model="dataForm.content"
            placeholder="请输入相关介绍"
            maxlength="500"
            show-word-limit
            resize="none"
          ></el-input>
        </el-form-item>
      </div>
    </el-form>

    <el-dialog v-model="dialogVisible" width="75%" top="5vh">
      <img
        style="max-width: 100%; max-height: 80vh; display: block; margin: 0 auto;"
        :src="dialogImageUrl"
        alt="相关图片预览"
      />
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false" size="large">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm()"
          size="large"
          :loading="submitting"
          :disabled="uploadingCount > 0">
          {{ submitting ? '提交中...' : '提交' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage } from "element-plus";
import baseService from "@/service/baseService";
import { Plus, Delete } from '@element-plus/icons-vue'

export default {
  name: "picAdd",
  components: { Plus, Delete },
  data() {
    return {
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      visible: false,
      submitting: false,
      uploadingCount: 0,
      uploadProgress: 0,
      institutionName: "",
      dataForm: {
        institutionId: "",
        content: "",
        picList: [] // 改为数组存储多个文件
      },
    };
  },
  methods: {
    init(id, institutionName) {
      this.visible = true;
      this.dataForm.institutionId = id;
      this.institutionName = `${institutionName} - 新增机构相关`;
      this.fileList = [];
      this.dataForm.picList = [];
      this.submitting = false;
      this.uploadingCount = 0;
      this.uploadProgress = 0;

      if (this.$refs.dataFormRef) {
        this.$refs.dataFormRef.resetFields();
      }
    },

    async handleChange(file, fileList) {
      if (file.size > 5 * 1024 * 1024) {
        ElMessage.error("图片大小不能超过5MB");
        return false;
      }

      this.fileList = fileList;
    },

    beforeRemove(file) {
      return ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
    },

    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
        this.dataForm.picList = this.dataForm.picList.filter(
          item => item.uid !== file.uid
        );
      }
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url || URL.createObjectURL(file.raw);
      this.dialogVisible = true;
    },

    async uploadFiles() {
      this.uploadingCount = 0;
      this.uploadProgress = 0;
      const totalFiles = this.fileList.length;

      if (totalFiles === 0) {
        return true;
      }

      this.uploadingCount = totalFiles;

      try {
        const uploadPromises = this.fileList.map(async (file, index) => {
          if (!file.raw) {
            // 已经是上传过的文件
            this.uploadingCount--;
            return file.response?.data;
          }

          const formdata = new FormData();
          formdata.append("file", file.raw);

          const response = await baseService.post(
            "sdl/institutionqaq/upload/image",
            formdata,
            { "Content-Type": "multipart/form-data" }
          );

          this.uploadingCount--;
          this.uploadProgress = Math.round(((totalFiles - this.uploadingCount) / totalFiles) * 100);

          if (response.code === 0) {


            return response.data;
          } else {
            throw new Error(response.msg || "图片上传失败");
          }
        });

        const results = await Promise.all(uploadPromises);
        this.dataForm.picList = results.filter(Boolean);
        console.log("图片文件地址",  this.dataForm.picList);
        return true;
      } catch (error) {
        ElMessage.error(error.message || "上传过程中出错");
        return false;
      }
    },

    async submitForm() {
      try {
        const valid = await this.$refs.dataFormRef.validate();
        if (!valid) return;

        if (this.fileList.length === 0) {
          ElMessage.warning("请至少上传一张机构相关图片");
          return;
        }

        this.submitting = true;

        // 先上传所有文件
        const uploadSuccess = await this.uploadFiles();
        console.log("图片文件", this.dataForm);
        if (!uploadSuccess) return;

        // 提交表单数据
        const resp = await baseService.post("sdl/institutionPic/save", this.dataForm);

        if (resp.code === 0) {
          ElMessage.success("保存成功");
          this.$emit("refresh");
          this.resetForm();
        } else {
          ElMessage.error(resp.msg || "保存失败");
        }
      } catch (error) {
        ElMessage.error(error.message || "提交服务异常");
      } finally {
        this.submitting = false;
      }
    },

    resetForm() {
      this.fileList = [];
      this.dataForm.picList = [];
      this.visible = false;
    }
  }
};
</script>

<style scoped lang="scss">
.institution-dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #f0f0f0;
    margin-right: 0;
    padding: 16px 24px;
  }

  :deep(.el-dialog__body) {
    padding: 20px 24px;
  }

  .form-content {
    padding: 0 12px;
  }

  .upload-item {
    margin-bottom: 24px;

    :deep(.el-form-item__label) {
      padding-bottom: 8px;
      font-weight: 500;
    }

    .upload-container {
      display: flex;
      gap: 20px;
      align-items: flex-start;
    }
  }

  .qualification-upload {
    flex: 1;

    :deep(.el-upload) {
      width: 148px;
      height: 148px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      background-color: #fafafa;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
        background-color: #f5f9ff;
      }
    }

    :deep(.el-upload-list--picture-card) {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin: 0;
    }

    :deep(.el-upload-list__item) {
      width: 148px;
      height: 148px;
      margin: 0;
    }

    .upload-icon {
      font-size: 28px;
      color: #8c939d;
      margin-bottom: 12px;
    }

    .upload-tip {
      color: #606266;
      font-size: 14px;
      text-align: center;
    }

    .uploaded-image {
      width: 100%;
      height: 100%;
      position: relative;

      &-el {
        width: 100%;
        height: 100%;
        object-fit: cover;
        cursor: pointer;
      }

      &-actions {
        position: absolute;
        top: 0;
        right: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        opacity: 0;
        transition: opacity 0.3s;
        display: flex;
        justify-content: center;
        align-items: center;

        &:hover {
          opacity: 1;
        }
      }

      &-delete {
        color: #fff;
        font-size: 20px;
        cursor: pointer;

        &:hover {
          color: #ff4d4f;
        }
      }
    }
  }

  .upload-hint {
    flex: 0 0 220px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;

    .hint-title {
      font-weight: 500;
      margin-bottom: 8px;
      color: #333;
    }

    .hint-list {
      margin: 0;
      padding-left: 18px;
      color: #666;
      font-size: 13px;
      line-height: 1.6;

      li {
        margin-bottom: 4px;
      }
    }

    .upload-progress {
      margin-top: 16px;

      .progress-text {
        font-size: 12px;
        color: #666;
        margin-bottom: 6px;
      }
    }
  }

  .description-item {
    :deep(.el-textarea__inner) {
      min-height: 120px !important;
    }
  }

  .dialog-footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    text-align: right;

    .el-button {
      min-width: 100px;
    }
  }
}
</style>
